package com.conorroche.taskmanagement;

import java.io.IOException;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AddTask extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		extras = getIntent().getExtras();
		setContentView(R.layout.activity_add_task);
		SetupButtons();
	}
	@Override
	protected Dialog onCreateDialog(int id){
		switch(id){
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, hour, minute, true);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, yr, month, day);
		case GEOCODE_DIALOG_ID:
			geocoder = new Geocoder(this, Locale.getDefault());
			try{
				List<Address> addressList = geocoder.getFromLocationName(taskLocation.getText().toString(), 5);
				Iterator<Address> addressIt = addressList.iterator();
				Address[] tempAddresses = new Address[5];
				int c = 0;
				while(addressIt.hasNext()){
					tempAddresses[c] = addressIt.next();
					c++;
				}
				addresses = new String[c];
				address = new Address[c];
				for(int i = 0; i < c; i++){
					addresses[i] = "";
					for(int j = 0; j < tempAddresses[i].getMaxAddressLineIndex(); j++){
						addresses[i] = addresses[i] + " " + tempAddresses[i].getAddressLine(j);
						address[i] = tempAddresses[i];
					}
					addresses[i] = addresses[i] + " " + tempAddresses[i].getCountryName();
					Log.d("AddTask", addresses[i]);
				}
				alert = new AlertDialog.Builder(this).setIcon(R.drawable.location_place)
					.setTitle("Please select your location")
					.setPositiveButton("OK", new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int whichButton){
						
						}
					})
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton){
							addresses = null;
							geocoder = null;
							alert = null;
						}
					})
					.setSingleChoiceItems(addresses, 0, new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog, int which) {
							latitude = address[which].getLatitude();
							longitude = address[which].getLongitude();
							taskLocation.setText(addresses[which]);
						}
					})
					.create();
				return alert;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
  
	protected DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			yr = year;
			month = monthOfYear;
			day = dayOfMonth;
			dateButton.setText((day < 10 ? "0" + day: day) + "/" + (month < 9 ? "0" + (month + 1) : (month + 1)) + "/" + year);
		}
	};
	protected TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minuteOfHour) {
			hour = hourOfDay;
			minute = minuteOfHour;
			timeButton.setText((hour < 9 ? "0" + hour : hour) + ":" + (minute < 9 ? "0" + minute : minute));
		}
	};
	private void SetupButtons(){
		
		taskName = (TextView) findViewById(R.id.new_task_name);
		taskLocation = (AutoCompleteTextView) findViewById(R.id.new_task_location);
		timeButton = (Button) findViewById(R.id.new_task_time);
		dateButton = (Button) findViewById(R.id.new_task_date);
		taskNotes = (TextView) findViewById(R.id.new_task_notes);
		locationReminder = (CheckBox) findViewById(R.id.new_task_location_reminder);
		dateReminder = (CheckBox) findViewById(R.id.new_task_date_reminder);
		locationButton = (ImageButton) findViewById(R.id.new_task_get_location);
		okButton = (Button) findViewById(R.id.new_task_ok);
		cancelButton = (Button) findViewById(R.id.new_task_cancel);
		importanceSpinner = (Spinner) findViewById(R.id.new_task_tags);
		
		//Setup the date and time buttons
		dateButton.setText((day < 10 ? "0" + day : day) + "/" + (month < 9 ? "0" + (month + 1) : (month + 1)) + "/" + yr);
		timeButton.setText((hour < 10 ? "0" + hour: hour)  + ":" + (minute < 10 ? "0" + minute: minute));
		TagsHelper helper = new TagsHelper(getApplicationContext());
		tags = helper.getTags();
		if(tags == null){
			Log.d("Add task","There's something a little broken here");
				tags = new String[5];
				tags[0] = "Very Important";
				tags[1] = "Important";
				tags[2] = "College";
				tags[3] = "Not Important";
				tags[4] = "Home";
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, tags);
		importanceSpinner.setAdapter(adapter);
		importanceSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
				int index = arg0.getSelectedItemPosition();
				selectedTag = tags[index];
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
		locationButton.setOnClickListener(new View.OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				geocoder = null;
				alert = null;
				showDialog(GEOCODE_DIALOG_ID);
			}
		});
		okButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				storeData();
				if(!error){
					finish();
				}else{
					
				}
			}
		});
		cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		timeButton.setOnClickListener(new View.OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});
		dateButton.setOnClickListener(new View.OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		
		if(extras.getBoolean("edit")){
			taskName.setText(extras.getString("name"));
			timeButton.setText(extras.getString("time"));
			dateButton.setText(extras.getString("date"));
			taskNotes.setText(extras.getString("notes"));
			taskLocation.setText(extras.getString("location"));
			if(extras.containsKey("dateRemind") && extras.getInt("dateRemind") == 1){
				dateReminder.setChecked(true);
			}
			if(extras.containsKey("locationRemind") && extras.getInt("locationRemind") == 1){
				locationReminder.setChecked(true);
			}
		}
	}
	
	private void storeData(){
		if(!taskName.getText().toString().equals("") && isValid(taskName.getText().toString())){
			db = new DBAdapter(getApplicationContext());
			db.open();
			if(extras.getBoolean("edit")){
				db.updateTask(extras.getInt("id"), taskName.getText().toString(), taskLocation.getText().toString(), selectedTag, timeButton.getText().toString(),
						dateButton.getText().toString(), taskNotes.getText().toString(), locationReminder.isChecked(), 
						dateReminder.isChecked(), "On time", false, longitude, latitude);
				Toast.makeText(getApplicationContext(), taskName.getText().toString() + " has been updated", Toast.LENGTH_SHORT).show();
			}else{
				id = db.insertTask(taskName.getText().toString(), taskLocation.getText().toString(), selectedTag , timeButton.getText().toString(), dateButton.getText().toString(), 
						taskNotes.getText().toString(), locationReminder.isChecked(), dateReminder.isChecked(), "0", false, longitude, latitude);
				Toast.makeText(getApplicationContext(), taskName.getText().toString() + " has been saved", Toast.LENGTH_SHORT).show();
			}
			db.close();
			if(dateReminder.isChecked()){
				Intent notificationService = new Intent(getApplicationContext(), NotificationService.class);
				notificationService.putExtra("id", id);
				notificationService.putExtra("name", taskName.getText().toString());
				notificationService.putExtra("time", true);
				notificationService.putExtra("location", false);
			
				Calendar cal = Calendar.getInstance();
				cal.set(yr, month, day);
				cal.set(Calendar.HOUR, hour);
				cal.set(Calendar.MINUTE, minute);
				cal.set(Calendar.SECOND, 0);
			
				PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, notificationService, 0);
			
				AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
				am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
			}
			if(locationReminder.isChecked()){
				Intent notificationService = new Intent(getApplicationContext(), NotificationService.class);
				notificationService.putExtra("id", id);
				notificationService.putExtra("name", taskName.getText().toString());
				notificationService.putExtra("time", dateReminder.isChecked()?true:false);
				notificationService.putExtra("location", locationReminder.isChecked()?true:false);
			
				PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, notificationService, 0);
			
				LocationManager lm = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
				lm.addProximityAlert(latitude, longitude, 20, -1, pendingIntent);
			
			}
			if(!(MainActivity.tasksHelper == null)){
				MainActivity.tasksHelper.updateAdapter(taskName.getText().toString());
			}
		}else{
			error = true;
			Toast.makeText(getApplicationContext(), "You must enter a valid name", Toast.LENGTH_SHORT).show();
		}
	}
	public boolean isValid(String str){
		boolean isValid = false;
		String expression = "^[a-z_A-Z0-9 ]*$";
        CharSequence inputStr = str;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if(matcher.matches()){
        	isValid = true;
        }
        return isValid;
     }
 
    private TextView taskName, taskNotes;
    private AutoCompleteTextView taskLocation;
	private Button timeButton, dateButton, okButton, cancelButton;
	private CheckBox locationReminder, dateReminder;
	private ImageButton locationButton;
	private Bundle extras;
	private long id;
	private DBAdapter db;
	private Geocoder geocoder;
	private AlertDialog alert;
	private Spinner importanceSpinner;
	private static String[] addresses;
	private Address[] address;
	private String[] tags;
	
	private Calendar today = Calendar.getInstance();
	private int yr = today.get(Calendar.YEAR);
	private int month = today.get(Calendar.MONTH);
	private int day = today.get(Calendar.DAY_OF_MONTH);
	private int hour = today.get(Calendar.HOUR);
	private int minute = today.get(Calendar.MINUTE);
	
	static final int TIME_DIALOG_ID = 0;
	static final int DATE_DIALOG_ID = 1;
	static final int GEOCODE_DIALOG_ID = 2;
	
	private String selectedTag = "Important";
	private double latitude = 0;
	private double longitude = 0;
	private boolean error = false;
	
	protected TimePicker timePicker;
	protected DatePicker datePicker;
	
}
